package com.manager.devicemanager.controller;

import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.manager.devicemanager.common.DataSourceNameEnum;
import com.manager.devicemanager.common.ICComponentPriority;
import com.manager.devicemanager.common.Result;
import com.manager.devicemanager.config.DeviceConfig;
import com.manager.devicemanager.entity.*;
import com.manager.devicemanager.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 新大屏的接口实现
 */
@RestController()
@RequestMapping("/dashboard")
public class DashboardController {
    @Autowired
    private IDeviceInfoService iDeviceInfoService;
    @Autowired
    private IStatusaccountingService statussAccountingService;
    @Autowired
    private ITestbatchService testbatchService;
    @Autowired
    private IRealtimedevicestatusService realtimedevicestatusService;
    @Autowired
    private DeviceConfig deviceConfig;
    @Autowired
    private IDevicestatusService iDevicestatusService;
    @Autowired
    private IIcBoardTypeService iIcBoardTypeService;



    /**
     * 获取设备信息以及运行信息
     *
     * @return 设备信息以及运行信息
     */
    @PostMapping("/getDeviceInfoAndRunInfo")
    private Result<List<JSONObject>> getDeviceInfoAndRunInfo() {
        LambdaQueryWrapper<DeviceInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.orderByAsc(DeviceInfo::getDeviceindex);
        List<DeviceInfo> deviceInfoList = iDeviceInfoService.list(queryWrapper);
        Date endtime = new Date();
        List<JSONObject> deviceRunInfoStream = deviceInfoList.stream().map(deviceInfo1 -> {
            JSONObject from = JSONObject.from(deviceInfo1);
            String dataSourceName = "ic".equals(deviceInfo1.getType()) ? DataSourceNameEnum.ICBOARDCONFIG.getDataSourceName() + deviceInfo1.getDatasourceindex() : DataSourceNameEnum.PDBOARDCONFIG.getDataSourceName() + deviceInfo1.getDatasourceindex();
            Statusaccounting dataLastIc = null;
            try {

                dataLastIc = statussAccountingService.getDataLast(dataSourceName);
            } catch (Exception e) {
                System.out.println("获取最新数据异常：" + e.getMessage());
                dataLastIc = new Statusaccounting();
                dataLastIc.setTotalDevices(0);
                dataLastIc.setStatusCnt1(0);
                dataLastIc.setStatusCnt2(0);
                dataLastIc.setStatusCnt3(0);
                dataLastIc.setStatusCnt4(0);
            }
            long runDays = 0L;
            String systemvoltage = null;
            try {
                Testbatch testbatch = testbatchService.getLastData(dataSourceName);
                if (testbatch != null) {
                    Date starttime = testbatch.getStarttime();
                    long diff = endtime.getTime() - starttime.getTime();
                    runDays = diff / (1000 * 60 * 60 * 24);
                    systemvoltage = testbatch.getSystemvoltage();
                }
            } catch (Exception e) {
                System.out.println("获取运行天数异常：" + e.getMessage());
            }
            Realtimedevicestatus realtimedevicestatus = null;
            try {
                realtimedevicestatus = realtimedevicestatusService.getDataLastIc(dataSourceName);
                from.put("isOffline", true);
                from.put("storageStatus", realtimedevicestatus == null || realtimedevicestatus.getStorageStatus() == null ? "0" : realtimedevicestatus.getStorageStatus());
                if (realtimedevicestatus != null) {
                    Date updateTime = realtimedevicestatus.getUpdateTime();
                    // 获取当前时间
                    Date currentTime = new Date();
                    // 计算时间差（毫秒）
                    long diff = currentTime.getTime() - updateTime.getTime();
                    // 5 分钟的毫秒数
                    long fiveMinutesInMillis = deviceConfig.getMinutes() * 60 * 1000;
                    // 判断时间差是否超过 5 分钟
                    if (diff > fiveMinutesInMillis) {
                        // 设备离线逻辑，这里可以设置离线状态，例如添加一个 isOffline 属性到 DeviceInfoVO
                        from.put("isOffline", true);
                    } else {
                        from.put("isOffline", false);
                    }
                }
            } catch (Exception e) {
                System.out.println("获取实时设备状态异常：" + e.getMessage());
                from.put("storageStatus", "0");
                from.put("isOffline", true);
            }

            from.put("systemvoltage", systemvoltage);

            from.put("runDays", runDays);
            from.put("dataLastIc", dataLastIc);
            return from;
        }).collect(Collectors.toList());
        return Result.success(deviceRunInfoStream);
    }

    @PostMapping("/getBoardStatus")
    private Result<List<JSONObject>> getBoardStatus() {
        LambdaQueryWrapper<DeviceInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.orderByAsc(DeviceInfo::getDeviceindex);
        List<DeviceInfo> deviceInfoList = iDeviceInfoService.list(queryWrapper);
        List<JSONObject> deviceRunInfoStream = deviceInfoList.stream().map(deviceInfo1 -> {
            JSONObject from = JSONObject.from(deviceInfo1);
            String dataSourceName = "ic".equals(deviceInfo1.getType()) ? DataSourceNameEnum.ICBOARDCONFIG.getDataSourceName() + deviceInfo1.getDatasourceindex() : DataSourceNameEnum.PDBOARDCONFIG.getDataSourceName() + deviceInfo1.getDatasourceindex();
            Devicestatus devicestatus = null;
            try {
                devicestatus = iDevicestatusService.getDataList(dataSourceName);
            } catch (Exception e) {
                devicestatus = new Devicestatus();
                System.out.println("获取实时设备状态异常：" + e.getMessage());
            }

            if ("ic".equals(deviceInfo1.getType())) {
                from.put("b1", convertICStatusValue(devicestatus.getB1()));
                from.put("b2", convertICStatusValue(devicestatus.getB2()));
                from.put("b3", convertICStatusValue(devicestatus.getB3()));
                from.put("b4", convertICStatusValue(devicestatus.getB4()));
                from.put("b5", convertICStatusValue(devicestatus.getB5()));
                from.put("b6", convertICStatusValue(devicestatus.getB6()));
                from.put("b7", convertICStatusValue(devicestatus.getB7()));
                from.put("b8", convertICStatusValue(devicestatus.getB8()));
                from.put("b9", convertICStatusValue(devicestatus.getB9()));
                from.put("b10", convertICStatusValue(devicestatus.getB10()));
                from.put("b11", convertICStatusValue(devicestatus.getB11()));
                from.put("b12", convertICStatusValue(devicestatus.getB12()));
                from.put("types", iIcBoardTypeService.getAll(DataSourceNameEnum.ICBOARDCONFIG.getDataSourceName()+ deviceInfo1.getDatasourceindex()));
            } else {
                from.put("b1", devicestatus.getB1());
                from.put("b2", devicestatus.getB2());
                from.put("b3", devicestatus.getB3());
                from.put("b4", devicestatus.getB4());
                from.put("b5", devicestatus.getB5());
                from.put("b6", devicestatus.getB6());
                from.put("b7", devicestatus.getB7());
                from.put("b8", devicestatus.getB8());
                from.put("b9", devicestatus.getB9());
                from.put("b10", devicestatus.getB10());
                from.put("b11", devicestatus.getB11());
                from.put("b12", devicestatus.getB12());
                from.put("b13", devicestatus.getB13());
                from.put("b14", devicestatus.getB14());
                from.put("b15", devicestatus.getB15());
                from.put("b16", devicestatus.getB16());
                from.put("b17", devicestatus.getB17());
                from.put("b18", devicestatus.getB18());
            }
            return from;
        }).collect(Collectors.toList());
        return Result.success(deviceRunInfoStream);
    }

    // 添加状态值转换方法
    private String convertICStatusValue(String value) {
        if (value == null) {
            return "断电";
        }
        switch (value) {
            case "0":
                return "正常";
            case "1":
                return "断电";
            case "6":
                return "闩锁";
            case "8":
            case "9":
            case "10":
                return "翻转";
            default:
                return "断电";
        }
    }

    @PostMapping("/lastsixmonth")
    public Result<List<JSONObject>> getLastSixMonths() {
        LambdaQueryWrapper<DeviceInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.orderByAsc(DeviceInfo::getDeviceindex);
        List<DeviceInfo> deviceInfoList = iDeviceInfoService.list(queryWrapper);
        List<JSONObject> deviceRunInfoStream = deviceInfoList.stream().map(deviceInfo1 -> {
            JSONObject from = JSONObject.from(deviceInfo1);
            String dataSourceName = "ic".equals(deviceInfo1.getType()) ? DataSourceNameEnum.ICBOARDCONFIG.getDataSourceName() + deviceInfo1.getDatasourceindex() : DataSourceNameEnum.PDBOARDCONFIG.getDataSourceName() + deviceInfo1.getDatasourceindex();
            List<Statusaccounting> statusaccountingList = statussAccountingService.getLastSixMonths(dataSourceName);
            from.put("statusaccountingList", statusaccountingList);
            return from;
        }).collect(Collectors.toList());
        return Result.success(deviceRunInfoStream);
    }
}
